<?php

/**
 * compte actions.
 *
 * @package    explications_informatiques
 * @subpackage compte
 * @author     Guimezanes Cyrille
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class compteActions extends sfActions
{
  public function executeIndex(sfWebRequest $request)
  {
	$this->forwardUnless($this->getUser()->isAuthenticated(),"headers","forbidden");
	$q = Doctrine_Query::create()
	->from('clientsplatforms n')
	->leftJoin("n.Platform")
	->leftJoin("n.Platformgroup pg")
	->where('n.id_client = ?', $this->getUser()->getGuardUser()->getId())
	->orderBy('pg.ordre asc');
	$this->platformClient = $q->execute();
	
	$q = Doctrine_Query::create()
	->from('adverts n')
	->where('n.id_membre = ?', $this->getUser()->getGuardUser()->getId())
	->leftJoin("n.SfGuardUserProfile p")
	->leftJoin("n.SfGuardGroup")
	->leftJoin("p.User");
	
	$this->adverts = $q->execute();
  }
  public function executeSelectlevel(sfWebRequest $request)
  {
	  
  }
  public function executeLevel(sfWebRequest $request)
  {
	  if($request->getParameter("lvl"))
	  {
		  $q = Doctrine_Query::create()
			->from('clientsplatforms n')
			->where('n.id_client = ?', $this->getUser()->getGuardUser()->getId());
		  $q->delete();
		  $collection = new Doctrine_Collection('clientsplatforms');
		  
		  if($request->getParameter("lvl") == "1")
		  {
			 $values = array(
							  array(3,106,1),
							  array(25,126,2),
							  array(39,158,3),
							  array(42,166,4),
							  array(47,180,5),
							  array(54,NULL,6),
							  array(59,NULL,7),
			 				);
		  }
		  elseif ($request->getParameter("lvl") == "2")
		  {
			   $values = array(
							  array(3,106,1),
							  array(25,126,2),
			 				);
		  }
			foreach($values as $val_deb)
			{
			 $index = new Clientsplatforms();
			 $index->setIdClient($this->getUser()->getGuardUser()->getId());
			 $index->setIdPlatform($val_deb[0]);
			 if($val_deb[1] != NULL)
			 	$index->setVersion($val_deb[1]);
			 $index->setIdGroupPlatform($val_deb[2]);
			 $collection->add($index);
			}
		  $collection->save();
		  //Log
	  	sfCoreAutoload::logElem("Création d'un compte", $this->getUser()->getGuardUser()->getId(), date("Y-m-d h:i:s"));
	  }
	  $this->redirect("compte/index");
  }
  public function executeShow(sfWebRequest $request)
  {
	$this->forwardUnless($this->getUser()->isAuthenticated() && $this->getUser()->hasCredential("VIEW_PROFIL"),"headers","forbidden");
    $q = Doctrine_Query::create()
	->from('sfGuardUserProfile n')
	->leftJoin("n.User")
	->where("id = ?",$request->getParameter('idprofil'));
	$this->profil = $q->fetchOne();
	
	if ($this->getUser()->hasCredential("MOD_USER"))
	{
		$this->profil["view_by_mode"] = "1";
		$this->profil->save();
	}
	
	$q = Doctrine_Query::create()
	->from('clientsplatforms n')
	->leftJoin("n.Platform")
	->leftJoin("n.Platformgroup pg")
	->where('n.id_client = ?', $this->profil["user_id"])
	->orderBy('pg.ordre asc');
	$this->platformClient = $q->execute();
    $this->forward404Unless($this->profil);
	
  }

  

  public function executeEdit(sfWebRequest $request)
  {
	$this->forwardUnless($this->getUser()->isAuthenticated() && ($request->getParameter('id') == $this->getUser()->getGuardUser()->getId() ||  $this->getUser()->hasCredential("MODERATION_USER")),"headers","forbidden");
    $this->forward404Unless($sf_guard_user_profile = Doctrine_Core::getTable('sfGuardUserProfile')->findOneByUserId($request->getParameter('id')), sprintf('Object sf_guard_user_profile does not exist (%s).', $request->getParameter('id')));
    //var_dump($sf_guard_user_profile);
	$this->form = new ProfilForm($sf_guard_user_profile);
	$this->form->setDefault('id', $request->getParameter('id'));
	
	$q = Doctrine_Query::create()
	->from('Platformgroup n')
	->leftJoin("n.Platform p")
	->leftJoin("p.Plateformversion")
	->leftJoin("n.Clientsplatforms cp ON cp.id_client = ".$this->getUser()->getGuardUser()->getId()." AND cp.id_group_platform = n.idtable2")
	->leftJoin("cp.Platform")
	->orderBy('n.ordre asc')
	->where("n.online = ?","1");
	
	$this->groups = $q->execute();
  }

  public function executeUpdate(sfWebRequest $request)
  {
	$this->forwardUnless($this->getUser()->isAuthenticated() && ($request->getParameter('id') == $this->getUser()->getGuardUser()->getId() ||  $this->getUser()->hasCredential("MODERATION_USER")),"headers","forbidden");
    $this->forwardUnless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT),"headers","forbidden");
    $this->forward404Unless($sf_guard_user_profile = Doctrine_Core::getTable('sfGuardUserProfile')->findOneByUserId($request->getParameter('id')), sprintf('Object sf_guard_user_profile does not exist (%s).', $request->getParameter('id')));
    $this->form = new ProfilForm($sf_guard_user_profile);
	$this->processForm($request, $this->form);
	
	//Log
	if($this->getUser()->hasCredential("MODERATION_USER"))
	  sfCoreAutoload::logElem("Edition d'un compte par un modo - id_membre:".$request->getParameter('id'), $this->getUser()->getGuardUser()->getId(), date("Y-m-d h:i:s"));
	
    $this->setTemplate('edit');
  }

  
  public function executeAutocomplete($request)
	 {
	   $this->getResponse()->setContentType('application/json');
	   				$req = Doctrine_Query::create()
					->from('sfGuardUser s')
	   				->leftJoin("s.Profile p")
					->where("s.username LIKE ?","%".$request->getParameter('q')."%")
					->andWhere("p.allow_mp = ?","1")
					->limit($request->getParameter('limit'))
					->execute()
					->getData();
	 
	   $names = array();
	   foreach ( $req as $user )
		 $names[$user->id] = (string) $user;
	   
	   return $this->renderText(json_encode($names));
	 }	
  protected function processForm(sfWebRequest $request, sfForm $form)
  {
	  
    $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
    
	if ($form->isValid())
    {
      if(!empty($request["profile"]["id"]))
	  	$sf_guard_user_profile = Doctrine_Core::getTable('sfGuardUserProfile')->findOneByUserId($request["profile"]["id"]);
	  else
	  	$sf_guard_user_profile = new SfGuardUserProfile();
	  
	  $sf_guard_user_profile->setWebsite($request["profile"]["website"]);
	  $sf_guard_user_profile->setSignature($request["profile"]["signature"]);
	  if(isset($request["profile"]["allow_mp"]))
	  	$sf_guard_user_profile->setAllowMp($request["profile"]["allow_mp"]);
	  else
		$sf_guard_user_profile->setAllowMp("0");
	  
	  if(isset($request["profile"]["allow_mail"]))
	  	$sf_guard_user_profile->setAllowMail($request["profile"]["allow_mail"]);
	  else
		$sf_guard_user_profile->setAllowMail("0");
	  $sf_guard_user_profile->setUpdatedAt(date("Ymdhis"));
	 
	  if($this->form->getValue('photo_delete'))
	  {
		  if(is_file($sf_guard_user_profile->getPhotoDirSrc().$sf_guard_user_profile->getPhoto()))
			unlink($sf_guard_user_profile->getPhotoDirSrc().$sf_guard_user_profile->getPhoto());
	  	$sf_guard_user_profile->setPhoto("");
	  }
	  elseif($this->form->getValue('photo'))
	  {
		if(is_file($sf_guard_user_profile->getPhotoDirSrc().$sf_guard_user_profile->getPhoto()))
			unlink($sf_guard_user_profile->getPhotoDirSrc().$sf_guard_user_profile->getPhoto());
	  	$name = $this->form->getValue('photo')->save();
		
		$sf_guard_user_profile->setPhoto($name);
		//move_uploaded_file($this->form->getValue('photo')->getTempName(), "images/avatar/".$name);
		//die();
		
	  }
	  if (empty($request["profile"]["skin"]))
	  	$sf_guard_user_profile->setSkin(1);
	  else
	  	$sf_guard_user_profile->setSkin($request["profile"]["skin"]); 
	  $sf_guard_user_profile->save();
	  
	  $old_plat = Doctrine_Core::getTable('clientsplatforms')->findByIdClient($this->getUser()->getGuardUser()->getId());
	  $old_plat->delete();
	  
	  $q = Doctrine_Query::create()
		->from('platformgroup');

	  $Groupplat = $q->execute();
	  $collection = new Doctrine_Collection('clientsplatforms');
	  foreach($Groupplat as $group)
	  { 
		  
		  if(isset($request["platform_".$group["idtable2"]]) && $request["platform_".$group["idtable2"]] != "x")
		  {
			  
			  $platclient = new Clientsplatforms();
			  $platclient->setIdClient($this->getUser()->getGuardUser()->getId());
			  $platclient->setIdPlatform($request["platform_".$group["idtable2"]]);
			  if(isset($request["version_".$group["idtable2"]]) && $request["version_".$group["idtable2"]] != "x")
			  	$platclient->setVersion($request["version_".$group["idtable2"]]);
				
			  $platclient->setIdGroupPlatform($group["idtable2"]);
			  $collection->add($platclient);
			  
		  }
	  }
	  $collection->save();
	  if ($cache = $this->getContext()->getViewCacheManager())
		{	
		  	$cache->remove('@sf_cache_partial?module=headers&action=_newmp&sf_cache_key='.$this->getUser()->getGuardUser()->getId());
			$cache->remove('compte/show?id='.$this->getUser()->getGuardUser()->getId());
		}
	  if($request->getParameter('action') == "create")
	  	$this->getUser()->setFlash("info","Compte utilisateur créé");
	  else
	  	$this->getUser()->setFlash("info","Compte utilisateur modifié");
		
      $this->redirect('compte/edit?id='.$sf_guard_user_profile->getUserId());
    }
  }
  public function executeGetversion(sfWebRequest $request)
  {
	   if ($request->isXmlHttpRequest())
		{
			$idplatforme = $request->getParameter('id');
			
			$q = Doctrine_Query::create()
				->from('plateformversion n')
				->where('n.platform = ?', $idplatforme)
				->orderBy('n.version asc');
			$this->choices = $q->execute();
			$this->group = $request->getParameter('group');
			return $this->renderPartial('getversion');
		}

  }
}
